package puzzeldoolhof;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

import weighteddirectedgraph.WeightedDirectedGraph;

public class Game 
{
	private WeightedDirectedGraph<Position, Color> my_maze;
	private Position Pdoel =  new Position( 0, Color.ORANGE );
	private Position Pvast =   new Position( 0, Color.WHITE );
	private State vast = new State( Pvast, Pvast );
	private State doel  = new State( Pdoel, Pdoel );
	
	public void setMaze( WeightedDirectedGraph<Position, Color> spel )
	{
		my_maze = spel;
	}
	
	public List<State> findPath( State current, Position finish )
	{
		List<State> visited = new ArrayList<State>();
		return findPath( current, finish, visited );
	}
	
	private List<State> findPath( State current, Position finish, List<State> visited )
	{
		visited.add( current );
		if ( current.getPosition1().equals( finish ) || current.getPosition2().equals( finish ) )
			return visited;
		
		for ( State nextMove : getPossibleMoves( current, visited ) )
		{
			List<State> possibleSolution = findPath( nextMove, finish, visited );
			
			if ( !possibleSolution.isEmpty() )
				return possibleSolution;
		}

		return new ArrayList<State>();
	}
	
	private List<State> getPossibleMoves( State current, List<State> visited)
	{
		List<State> next = new ArrayList<State>();
		
		addPossibleMoves( current.getPosition1(), current.getPosition2(), visited, next );
		addPossibleMoves( current.getPosition2(), current.getPosition1(), visited, next );

		return next;
	}
	
	private void addPossibleMoves( Position from, Position other, List<State> visited, List<State> list)
	{
		for( Position p : my_maze.getNeighbourValues( from ) )
		{
			if ( p != other && my_maze.getCost( from, p ) == other.getColor() )
			{				
				if ( !visited.contains( new State( p, other ) ) )
					list.add( new State(  p, other ) );
			}		
		}
	}
}
